<template>
  <div id="user">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>用户管理</span>
      </div>
      <el-form inline ref="form" :model="form" label-width="80px">
        <el-form-item label="关键字">
          <el-input @clear="cleartable($event, 'clear')" clearable style="width: 250px;" v-model="input" size="small"
            placeholder="请输入用户名称"></el-input>
        </el-form-item>
        <el-form-item label-width="0px">
          <el-button type="primary" size="small" @click="search" icon="el-icon-search">搜索</el-button>
          <el-button type="info" size="small" @click="cleartable($event)" icon="el-icon-search">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="5">
        <el-col :span="1.5">
          <el-button plain @click="addBtn()" type="primary" size="small" icon="el-icon-search">增加</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button @click="setUser(...checkboxall)" :disabled="checkboxall.length != 1" plain type="success"
            size="small" icon="el-icon-search">修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button @click="delUser()" :disabled="checkboxall.length == 0" plain type="danger" size="small"
            icon="el-icon-search">删除</el-button>
        </el-col>
      </el-row>

      <!-- 
        账号
        名称
        性别
        状态
        生日
        手机
       -->
      <el-table height="70%" ref="multipleTable" :data="tableData" show-overflow-tooltip tooltip-effect="dark"
        style="width: 100%;margin-bottom: 30px;" @selection-change="handleSelectionChange">
        <el-table-column align="center" type="selection" width="55">
        </el-table-column>
        <el-table-column align="center" label="头像">
          <template slot-scope="scope">
            <img v-if="scope.row.user_pic" :src="scope.row.user_pic" class="avatar">
          </template>
        </el-table-column>
        <el-table-column align="center" prop="username" label="账号">
        </el-table-column>
        <el-table-column align="center" prop="nickname" label="名称">
        </el-table-column>
        <el-table-column align="center" prop="cellphone" label="手机">
        </el-table-column>
        <!-- <el-table-column align="center" label="性别">
          <template slot-scope="scope">
            <el-tag :type="scope.row.sex == '女' ? 'success' : ''" size="medium">{{ scope.row.sex }}</el-tag>
          </template>
        </el-table-column> -->
        <el-table-column align="center" label="状态">
          <template slot-scope="scope">
            <el-switch :active-value="0" :inactive-value="1" @change="switch_value(scope.row)"
              v-model="scope.row.is_delete">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column :width="200" align="center" label="操作">
          <template slot-scope="scope">
            <el-button @click="setUser(scope.row)" size="small" type="primary" icon="el-icon-edit">修改</el-button>
            <el-button @click="delUser(scope.row)" size="small" type="danger" icon="el-icon-delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination style="text-align: center; margin-top: 20px;" @size-change="sizeChange"
        @current-change="currentChange" :current-page="pagination.pagenum" :page-sizes="pagination.pageSizes"
        :page-size="pagination.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total">
      </el-pagination>
    </el-card>


    <!-- 增加 -->
    <el-dialog :close-on-click-modal="false" width="600px" :title="isAdd ? '添加用户' : '修改用户'" :visible.sync="dialogVisible"
      @close="closedialog">
      <el-form :rules="rules" style="width: 100%;" ref="dialog_form" :model="dialog_form" label-width="60px">
        <el-row style="width: 100%;">
          <el-col :span="12">
            <el-form-item prop="username" label="账号">
              <el-input :disabled="!isAdd" v-model="dialog_form.username" size="small" placeholder="请输入账号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="password" label="密码" :rules="rules2">
              <el-input v-model="dialog_form.password" size="small" :placeholder="isAdd ? '请输入密码' : '不修改则不填'"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="nickname" label="昵称">
              <el-input v-model="dialog_form.nickname" size="small" placeholder="请输入昵称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="cellphone" label="手机">
              <el-input v-model="dialog_form.cellphone" size="small" placeholder="请输入手机"></el-input>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="头像">
              <el-upload class="avatar-uploader" action="#" :http-request="httpRequest" :show-file-list="false">
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-if="imageUrl" class="x el-icon-circle-close" @click.stop="closeIcon"></i>
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitdialog">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getUser, setUser, addUser, delUser } from '@/api/index'
export default {
  name: 'user',
  data() {
    let userrole = (rule, value, callback) => {
      if (!(/\w/.test(value))) {
        callback(new Error('请输入a-zA-Z0-9的字符串'));
      } else {
        callback();
      }
    };
    let phonerole = (rule, value, callback) => {
      if (!(/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(value))) {
        callback(new Error('请输入正确的手机号码'));
      } else {
        callback();
      }
    };
    return {
      input: '',
      tableData: [],
      multipleSelection: [],
      form: {},
      pagination: {
        pageSizes: [2, 4, 6, 8, 10],
        pageSize: 2,
        pagenum: 1,
        total: 0,
      },
      dialogVisible: false,
      dialog_form: {
        username: '',
        password: '',
        nickname: '',
        cellphone: '',
        user_pic: '',
      },
      isAdd: true,
      rules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' },
          { validator: userrole, trigger: 'blur' }
        ],
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
        ],
        cellphone: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: phonerole, trigger: 'blur' }
        ],
      },
      issearch: false,
      checkboxall: [],
      imageUrl: '',
    }
  },
  computed: {
    rules2() {
      let a = {
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
      }
      if (!this.isAdd) {
        a.password[0].required = this.isAdd
      }
      return a.password
    }
  },
  mounted() {
    this.getUser();
  },
  methods: {
    //获取用户
    getUser() {
      let data = {
        pagesize: this.pagination.pageSize,
        pagenum: this.pagination.pagenum,
        field: this.input
      }
      getUser(data).then((res) => {
        this.tableData = res.data.results;
        this.pagination.total = res.data.total;
      })
    },
    //修改pageSize
    sizeChange(e) {
      this.pagination.pageSize = e;
      this.getUser();
    },
    //修改pagenum
    currentChange(e) {
      this.pagination.pagenum = e;
      this.getUser();
    },
    //选中回调
    handleSelectionChange(val) {
      this.checkboxall = val;
    },
    //开关回调
    switch_value(row) {
      //通过id修改状态
      let data = {
        user_id: row.user_id,
        is_delete: row.is_delete
      }
      setUser(data).then((res) => {
        if (!res.data.status) {
          this.$message.error(res.data.message);
          row.is_delete = !row.is_delete
        }
      })
    },
    //关闭弹窗回调
    closedialog() {
      this.imageUrl = ''
      this.dialog_form.password = ''
      this.$refs.dialog_form.resetFields();
      this.$refs.dialog_form.clearValidate();
    },
    //弹框确定 增加 修改
    submitdialog() {
      this.$refs.dialog_form.validate((valid) => {
        if (valid) {
          //校验成功 判断是不是添加用户
          if (this.isAdd) {
            addUser(this.dialog_form).then((res) => {
              if (!res.data.status) {
                this.$message.error(res.data.message)
              } else {
                this.$message.success('添加成功')
                this.pagination.pagenum = 1;
                this.getUser();
                this.dialogVisible = false;
              }
            })
          } else {
            //是修改用户
            if (this.dialog_form.birthday) {
              this.dialog_form.birthday = this.$moment(this.dialog_form.birthday)
            }
            setUser(this.dialog_form).then((res) => {
              if (res.data.status) {
                this.$message.success('修改成功');
                this.getUser();
                this.dialogVisible = false;
              } else {
                this.$message.error('失败');
              }
            })
          }
        } else {
          //校验失败
        }
      })
    },
    //点击修改
    setUser(row) {
      this.isAdd = false;
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.dialog_form = {
          ...row
        }
        this.imageUrl = this.dialog_form.user_pic
      })
    },
    //搜索
    search() {
      this.pagination.pagenum = 1;
      this.issearch = true;
      this.getUser();
    },
    //重置
    cleartable(e, v) {
      if (!(v === 'clear')) {
        if (this.input) {
          this.pagination.pagenum = 1;
          this.input = ''
          this.getUser();
        }
      } else {
        this.pagination.pagenum = 1;
        this.getUser();
      }
    },
    //多选删除/删除
    delUser(row) {
      let delmsg
      if (row != undefined) {
        // 单删模式
        delmsg = [row.user_id]
      } else {
        // 多删模式
        delmsg = this.checkboxall.map((item, index) => {
          return item.user_id;
        });
      }
      delUser({ list: delmsg }).then((res) => {
        if (res.data.status) {
          this.$message.success(res.data.message)
          this.pagination.pagenum = 1;
          this.getUser();
        } else {
          this.$message.error(res.data.message)
        }
      })

    },
    //上传图片
    httpRequest(e) {
      let res = !e.file ? e.target.files[0] : e.file; //兼容原生和element 上传
      let reader = new FileReader()
      reader.readAsDataURL(res)
      reader.onload = () => {//加载完立即触发
        this.dialog_form.user_pic = this.imageUrl = reader.result; // base64字符串
      }
    },
    addBtn() {
      this.isAdd = true;
      this.dialogVisible = !this.dialogVisible
    },
    closeIcon() {
      this.imageUrl = ''
      this.dialog_form.user_pic = null
    }
  }
}

</script>

<style lang="less" src="./index.less" scoped></style>